package com.youcheng.service.admin;

import com.youcheng.constant.ErrorTips;
import com.youcheng.dao.Admin;
import com.youcheng.mapper.AdminMapper;
import com.youcheng.utils.Helper;
import com.youcheng.utils.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("adminService")
public class AdminServiceImpl implements AdminService{

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public Admin getByUsername(String username ,String password) {
        Admin admin = adminMapper.getByUsername(username);
        if(admin == null){
            throw MyException.commonReturn(ErrorTips.commonErrorCode , "账号不存在");
        }
        if(!password.equals(admin.getPassword())){
            throw MyException.commonReturn(ErrorTips.commonErrorCode , "密码错误");
        }
        String adminToken = Helper.createAdminToken(username);
        int tokenExpire = Helper.getTimeSecond() + 86400;
        admin.setToken(adminToken);
        admin.setToken_expire(tokenExpire);
        admin.setUpdate_at(Helper.getTimeSecond());
        admin.setLogin_times(admin.getLogin_times()+1);
        int i = adminMapper.updateById(admin);
        return admin;
    }

    @Override
    public int addAdmin(Admin admin) {
        Admin byUsername = adminMapper.getByUsername(admin.getUsername());
        if(byUsername != null){
            throw MyException.commonReturn(ErrorTips.commonErrorCode , "用户名已存在");
        }
        return adminMapper.addAdmin(admin);
    }

    @Override
    public int lockAdmin(int id,int is_lock) {
        Admin adminInfo = adminMapper.getById(id);
        if(adminInfo == null){
            throw MyException.commonReturn(ErrorTips.commonErrorCode , "数据不存在");
        }
        try {
            return adminMapper.lockAdmin(id,is_lock);
        }catch (Exception e){
            throw MyException.commonReturn(ErrorTips.commonErrorCode , "网络错误");
        }
    }

    @Override
    public List<Admin> listAllAdmin(String username,int is_lock) {
        List<Admin> admins = adminMapper.listAllAdmin(username, is_lock);
        return admins;
    }
}
